﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTime>
#pragma execution_character_set("utf-8")

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器端口：8888");
    udpSocket = new QUdpSocket(this); // 创建QUdpSocket套接字对象

    udpSocket->bind(8888); //绑定端口

    connect(udpSocket,&QUdpSocket::readyRead,this,&MainWindow::dealMsg);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::dealMsg()
{

    //读取对方发送的内容
       char buf[1024] = {0};           //内容
       QHostAddress cliAddr;           //对方地址
       quint16 port;                   //对方端口
       qint64 len = udpSocket->readDatagram(buf,sizeof(buf),&cliAddr,&port);
       //添加时间
       QTime cur_time = QTime::currentTime();
       QString time_info = cur_time.toString("hh:mm:ss");
       if(len >0)
       {
           //获取到文本格式化 如 [192.168.1.1 : 8888]aaaa 的格式
           QString str = QString("[%1:%2] %3 [%4]")
                   .arg(cliAddr.toString())
                   .arg(port)
                   .arg(buf)
                   .arg(time_info);
           ui->textEdit->append(str);
       }
}


void MainWindow::on_pB_send_clicked()
{
    QString ip = ui->lE_IP->text();
    qint16 port = ui->lE_port->text().toInt();
    QString str = ui->textEdit->toPlainText();
    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);
    ui->textEdit->clear();
}

void MainWindow::on_pB_close_clicked()
{
    udpSocket->disconnectFromHost();
    udpSocket->close();
    qDebug() << "主服务器连接断开！";
    this->close();
}
